package com.company.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.company.project.common.utils.DataResult;
import com.company.project.common.utils.Func;
import com.company.project.entity.*;
import com.company.project.mapper.*;
import com.company.project.service.*;
import com.company.project.vo.req.HomeTJReqVO;
import com.company.project.vo.resp.HomeRespVO;
import com.company.project.vo.resp.PermissionRespNode;
import com.company.project.vo.resp.ThrbTjRespVO;
import com.company.project.vo.resp.UserInfoRespVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 首页
 *
 * @author wenbin
 * @version V1.0
 * @date 2020年3月18日
 */
@Service
public class HomeServiceImpl implements HomeService {
    @Resource
    private UserService userService;
    @Resource
    private DeptService deptService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private SysRoleDeptMapper sysRoleDeptMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private RoleService roleService;
    @Resource
    private TSeatsService tSeatsService;
    @Resource
    private TSeatsMapper tSeatsMapper;
    @Resource
    private  THwtjService tHwtjService;
    @Resource
    private  TThrbMapper tThrbMapper;
    @Resource
    private TWdkhMapper tWdkhMapper;
    @Resource
    private TDailyMapper tDailyMapper;
    @Resource
    private TGzszMapper gzszMapper;

    @Override
    public HomeRespVO getHomeInfo(String userId) {

        SysUser sysUser = userService.getById(userId);
        TSeatsEntity tSeatsEntity = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getAccountid, sysUser.getId()));
        UserInfoRespVO vo = new UserInfoRespVO();
        vo.setTSeatsEntity(tSeatsEntity);
        if (sysUser != null) {
            BeanUtils.copyProperties(sysUser, vo);
            SysDept sysDept = deptService.getById(sysUser.getDeptId());
            if (sysDept != null) {
                vo.setDeptId(sysDept.getId());
                vo.setDeptName(sysDept.getName());
            }
        }

        List<PermissionRespNode> menus = permissionService.permissionTreeList(userId);

        LambdaQueryWrapper<SysRole> queryWrapper = Wrappers.lambdaQuery();
        LambdaQueryWrapper<SysUser> queryWrapperUser = Wrappers.lambdaQuery();

        if (!org.apache.commons.lang.StringUtils.equals("0",sysUser.getDeptId())) {
            //管理员可查看全部 其他能看自己下级
            SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId());
            if (sysDept == null) {//没有部门的查看自己公司的
                //获取用户公司名称
                String corporatename = tSeatsEntity.getCorporatename();
                List<Object> objects = tSeatsMapper.selectObjs(Wrappers.<TSeatsEntity>lambdaQuery().select(TSeatsEntity::getAccountid).eq(TSeatsEntity::getCorporatename, corporatename));
                queryWrapperUser.in(SysUser::getId,objects);
            } else {
                LambdaQueryWrapper<SysDept> queryWrapperDept = Wrappers.lambdaQuery();
                queryWrapperDept.select(SysDept::getId).like(SysDept::getRelationCode, sysDept.getDeptNo());
                //所有部门
                List<Object> deptList = sysDeptMapper.selectObjs(queryWrapperDept);
                if (!StringUtils.isEmpty(deptList)) {
                    LambdaQueryWrapper<SysRoleDeptEntity> queryWrapperRD = Wrappers.lambdaQuery();
                    queryWrapperRD.select(SysRoleDeptEntity::getRoleId).in(SysRoleDeptEntity::getDeptId,deptList);
                    //查询全部角色id
                    List<Object> roleIds = sysRoleDeptMapper.selectObjs(queryWrapperRD);
//                queryWrapper.in(SysRole::getId,roleIds);
                    queryWrapperUser.in(SysUser::getDeptId,deptList);
                }
            }
        }
        List<SysUser> sysUsers = sysUserMapper.selectList(queryWrapperUser);
        queryWrapper.orderByDesc(SysRole::getCreateTime);
        //获取自己的角色
        List<String> sysRoleNames = roleService.getRoleNames(userId);
        String s = sysRoleNames.get(0);//自己的角色/
        vo.setSysRoleName(sysRoleNames.get(0));

        List<Object> roleName = new ArrayList<>();
        //全部角色
        if (Func.equals("超级管理员",s)) {
            roleName.add("代理商");
            roleName.add("总经理");
            roleName.add("总监");
            roleName.add("主管");
            roleName.add("员工");
        } else if (Func.equals("代理商",s)) {
            roleName.add("总经理");
            roleName.add("总监");
            roleName.add("主管");
            roleName.add("员工");
        } else if (Func.equals("总经理",s)) {
            roleName.add("总监");
            roleName.add("主管");
            roleName.add("员工");
        } else if (Func.equals("销售总监",s)) {
            roleName.add("主管");
            roleName.add("员工");
        }
        List<SysRole> sysRolesList = new ArrayList<>();
        if (roleName.size()>0 ){
            queryWrapper.in(SysRole::getName,roleName);
            sysRolesList = sysRoleMapper.selectList(queryWrapper);
        }
        roleName = new ArrayList<>();
        /**
         * 超管角色添加坐席的时候，选择角色只能选择代理商和总经理这两个，
         * 代理商角色添加坐席页面只能添加总经理角色，
         * 总经理角色添加坐席选择角色能选择销售总监，主管，员工。
         * 销售总监添加只能选择主管和员工，
         */
        if (Func.equals("超级管理员",s)) {
            roleName.add("代理商");
            roleName.add("总经理");
        } else if (Func.equals("代理商",s)) {
            roleName.add("总经理");
        } else if (Func.equals("总经理",s)) {
            roleName.add("总监");
            roleName.add("主管");
            roleName.add("员工");
        } else if (Func.equals("销售总监",s)) {
            roleName.add("主管");
            roleName.add("员工");
        }
        queryWrapper.in(SysRole::getName,roleName);
        List<SysRole> sysRoles = new ArrayList<>();
        if(roleName.size()>0) sysRoles = sysRoleMapper.selectList(queryWrapper);

        //管理员可查看全部 其他能看自己下级
        List<SysDept> deptList = new ArrayList<>();
        //0 为管理员可以看全部的
        if(org.apache.commons.lang.StringUtils.equals("0",sysUser.getDeptId())){
            deptList = deptService.list();
        } else{
            SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId());
            LambdaQueryWrapper<SysDept> queryWrapperDept = Wrappers.lambdaQuery();
            if (sysDept == null) {
                queryWrapperDept.eq(SysDept::getUserid, userId);
            }else {
                queryWrapperDept.like(SysDept::getRelationCode, sysDept.getDeptNo());
            }
            //所有部门
            deptList = sysDeptMapper.selectList(queryWrapperDept);
        }
        THwtjEntity hwtj = tHwtjService.getDayData(s,sysUser);
        HomeRespVO respVO = new HomeRespVO();

        //每日一语
        List<TDailyEntity> tDailyEntities = tDailyMapper.selectList(Wrappers.<TDailyEntity>lambdaQuery());
        if (tDailyEntities.size()>0) {
            TDailyEntity tDailyEntity = tDailyEntities.stream()
                    .skip(new Random().nextInt(tDailyEntities.size()))
                    .findFirst()
                    .orElse(null);
            respVO.setMryy(tDailyEntity.getLanguage());
        }

        TGzszEntity tGzszEntity = gzszMapper.selectOne(Wrappers.<TGzszEntity>lambdaQuery().eq(TGzszEntity::getSsgs, tSeatsEntity.getCorporatename()));
        //是否隐藏
        List<SysRole> roleInfoByUserId = roleService.getRoleInfoByUserId(userId);
        List<String> collect = roleInfoByUserId.stream().map(e -> e.getName()).collect(Collectors.toList());
        if (Func.isNotEmpty(tGzszEntity)) {
            if (collect.contains("员工") || collect.contains("主管")) {
                respVO.setIsyc(tGzszEntity.getIsyc());
            }
        }
        respVO.setMenus(menus);
        respVO.setUserInfo(vo);
        respVO.setSysRole(sysRoles);
        respVO.setSysRoleList(sysRolesList);
        respVO.setDept(deptList);
        respVO.setUsers(sysUsers);
        respVO.setHwtj(hwtj);

        return respVO;
    }

    @Override
    public DataResult getHomeTongji(String time) {
        Map<String,Object> thrbtjMap = new HashMap<>();
        SysUser user = userService.getUserInfo();
        //角色
        List<SysRole> roleInfoByUserId = roleService.getRoleInfoByUserId(user.getId());
        List<String> collect = roleInfoByUserId.stream().map(e -> e.getName()).collect(Collectors.toList());

        List<ThrbTjRespVO> tjRespVO = tThrbMapper.selectTJ(user.getUsername(),time);
        List<String> xAxis = new ArrayList<>();
        List<String> bdcs = new ArrayList<>();
        List<String> jts = new ArrayList<>();
        List<String> thsc = new ArrayList<>();
        List<String> jfsc = new ArrayList<>();
        for (ThrbTjRespVO t: tjRespVO) {
            xAxis.add(t.getTime());
            bdcs.add(t.getBscs());
            jts.add(t.getJts());
            thsc.add(t.getThsc());
            jfsc.add(t.getJfsc());
        }

        thrbtjMap.put("xAxis",xAxis);
        thrbtjMap.put("bdcs",bdcs);
        thrbtjMap.put("jts",jts);
        thrbtjMap.put("thsc",thsc);
        thrbtjMap.put("jfsc",jfsc);

        return DataResult.success(thrbtjMap);
    }

    @Override
    public DataResult getJfcsqs(HomeTJReqVO vo) {
        SysUser user = userService.getUserInfo();
        //角色
        List<SysRole> roleInfoByUserId = roleService.getRoleInfoByUserId(user.getId());
        List<String> collect = roleInfoByUserId.stream().map(e -> e.getName()).collect(Collectors.toList());

        Calendar calendar = Calendar.getInstance();
        //时间
        if (Func.isNotEmpty(vo.getEndDate())) {
            calendar.setTime(vo.getEndDate());
            calendar.add(Calendar.DAY_OF_MONTH,1);
            vo.setEndDate(calendar.getTime());
        }
        List<TThrbEntity> tThrbEntities = new ArrayList<>();
        if (collect.contains("代理商")){
            tThrbEntities = tThrbMapper.selectJfscTj(user.getUsername(),vo);
        } else {
            tThrbEntities = tThrbMapper.selectJfscTj("",vo);
        }
        Map<String,Object> thrbtjMap = new HashMap<>();
        List<String> xAxis = new ArrayList<>();
        List<String> jfcs = new ArrayList<>();

        for (TThrbEntity t: tThrbEntities) {
            xAxis.add(t.getCompany());
            jfcs.add(t.getJfsc());
        }
        thrbtjMap.put("xAxis",xAxis);
        thrbtjMap.put("jfcs",jfcs);
        return DataResult.success(thrbtjMap);
    }

    @Override
    public DataResult getTseatsData() {
        SysUser user = userService.getUserInfo();
        //角色
        List<SysRole> roleInfoByUserId = roleService.getRoleInfoByUserId(user.getId());
        List<String> collect = roleInfoByUserId.stream().map(e -> e.getName()).collect(Collectors.toList());
        SysDept dept = sysDeptMapper.selectById(user.getDeptId());
        Integer zxcount = 0;
        Integer zx7,kh7,zx,kh = 0;
        if (collect.contains("代理商")){
            zx7 = tSeatsMapper.selectData(user.getUsername(),"7","主管","员工");
            kh7 = tSeatsMapper.selectData(user.getUsername(),"7","总经理","");
            zx = tSeatsMapper.selectData(user.getUsername(),"1","主管","员工");
            kh = tSeatsMapper.selectData(user.getUsername(),"1","总经理","");
            zxcount = tSeatsMapper.selectCountByUser("",dept.getDeptNo());
        } else {
            zx7 = tSeatsMapper.selectData("","7","主管","员工");
            kh7 = tSeatsMapper.selectData("","7","总经理","");
            zx = tSeatsMapper.selectData("","1","主管","员工");
            kh = tSeatsMapper.selectData("","1","总经理","");
            zxcount = tSeatsMapper.selectCountByUser("","");
        }
        Map<String,Object> map = new HashMap<>();
        Integer zxsltb = 0;
        Integer khsltb = 0;
        if (zx7 != 0) {
            zxsltb = (zx - zx7)/zx7;
        }
        if (kh7 != 0) {
            khsltb = (kh - kh7)/kh7;
        }
        map.put("zxsl",zx);
        map.put("zxsltb",zxsltb);
        map.put("khsl",kh);
        map.put("khsltb",khsltb);
        map.put("zxcount",zxcount);

        return DataResult.success(map);
    }

    @Override
    public DataResult getWdkhTJ(HomeTJReqVO vo) {
        SysUser user = userService.getUserInfo();
        //角色
        List<SysRole> roleInfoByUserId = roleService.getRoleInfoByUserId(user.getId());
        List<String> collect = roleInfoByUserId.stream().map(e -> e.getName()).collect(Collectors.toList());
        SysDept dept = sysDeptMapper.selectById(user.getDeptId());

        Calendar calendar = Calendar.getInstance();
        //时间
        if (Func.isNotEmpty(vo.getEndDate())) {
            calendar.setTime(vo.getEndDate());
            calendar.add(Calendar.DAY_OF_MONTH,1);
            vo.setEndDate(calendar.getTime());
        }
        List<TKhtjEntity> tKhtjEntities = new ArrayList<>();
        if (collect.contains("员工")){
            tKhtjEntities = tWdkhMapper.getWdkhTJ(user,vo,null);
        }else{
            tKhtjEntities = tWdkhMapper.getWdkhTJ(null,vo,dept);
        }

        Map<String,Object> thrbtjMap = new HashMap<>();
        List<String> xAxis = new ArrayList<>();
        List<String> xzkh = new ArrayList<>();
        List<String> xzyxkh = new ArrayList<>();

        for (TKhtjEntity t: tKhtjEntities) {
            xAxis.add(t.getTime());
            xzkh.add(t.getKhsl());
            xzyxkh.add(t.getYxdsl());
        }
        thrbtjMap.put("xAxis",xAxis);
        thrbtjMap.put("xzkh",xzkh);
        thrbtjMap.put("xzyxkh",xzyxkh);
        return DataResult.success(thrbtjMap);
    }

    @Override
    public DataResult getTwdkhData() {
        Map<String,Object> map = new HashMap<>();
        SysUser user = userService.getUserInfo();
        //角色
        List<SysRole> roleInfoByUserId = roleService.getRoleInfoByUserId(user.getId());
        List<String> collect = roleInfoByUserId.stream().map(e -> e.getName()).collect(Collectors.toList());
        SysDept dept = sysDeptMapper.selectById(user.getDeptId());
        Integer zxcount = 0;
        Integer addkh7,yxkh7,addkh,yxkh = 0;
        List<Map<String,String>> abcd = new ArrayList<>();
        if (collect.contains("员工")){
            abcd = tWdkhMapper.getKhlbByUser(user.getUsername(),"");
            addkh7 = tWdkhMapper.getWdkhCount("7","",user.getUsername());
            addkh = tWdkhMapper.getWdkhCount("1","",user.getUsername());
            yxkh7 = tWdkhMapper.getWdkhYxCount("7","",user.getUsername());
            yxkh = tWdkhMapper.getWdkhYxCount("1","",user.getUsername());
            zxcount = 1;
        } else {
            abcd = tWdkhMapper.getKhlbByUser("",dept.getDeptNo());
            addkh7 = tWdkhMapper.getWdkhCount("7",dept.getDeptNo(),"");
            addkh = tWdkhMapper.getWdkhCount("1",dept.getDeptNo(),"");
            yxkh7 = tWdkhMapper.getWdkhYxCount("7",dept.getDeptNo(),"");
            yxkh = tWdkhMapper.getWdkhYxCount("1",dept.getDeptNo(),"");
            zxcount = tSeatsMapper.selectCountByUser("",dept.getDeptNo());
        }

        Integer addkhsltb = 0;
        Integer yxkhsltb = 0;
        if (addkh7 != 0) {
            addkhsltb = (addkh - addkh7)/addkh7;
        }
        if (yxkh7 != 0) {
            yxkhsltb = (yxkh - yxkh7)/yxkh7;
        }
        map.put("addkh",addkh);
        map.put("addkhsltb",addkhsltb);
        map.put("yxkh",yxkh);
        map.put("yxkhsltb",yxkhsltb);
        map.put("abcd",abcd);
        map.put("zxcount",zxcount);

        return DataResult.success(map);
    }
}
